<?php

/* * ****************************************************************** */

// Project : MCS (2010)
//-------------------------------------------------------------------//
// Module  : Components
//-------------------------------------------------------------------//
// File    : common.php
//-------------------------------------------------------------------//
// Charset : UTF-8
//-------------------------------------------------------------------//
// Memo    :
//-------------------------------------------------------------------//
// Version : Add ( SONY  )  ( Jul 25, 2010 )
/* * ****************************************************************** */

class CommonComponent extends Object {

    var $Controller = null;

    //***************************************************************//
    // Function :
    //---------------------------------------------------------------//
    // Params   :
    //---------------------------------------------------------------//
    // Return   :
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( SONY ) ( Nov 22, 2008 )
    //***************************************************************//
    function startup(&$controller) {
        $this->Controller = & $controller;
    }

    function initialize(&$controller) {

    }

    function beforeRender($controller) {

    }

    function shutdown($controller) {

    }

    function beforeRedirect($controller, $url, $status = null, $exit = true) {

    }

    /**
     * Get Price
     */
    function getPriceFromString($string) {

        return str_replace(",", "", str_replace(".", '', $string));
    }

    /**
     * Dinh dang so
     *
     * @param type  meta
     * @return type  meta
     * @access public
     */
    function numberFormat($number, $decimals = 0) {
        return number_format($number, $decimals, ',', '.');
    }

    /**
     * Valid captcha
     *
     * @param type  meta
     * @return type  meta
     * @access public
     */
    function validCaptcha($name, $key_input) {
        // get key from session
        $key = $this->Controller->Session->read($name);

        // compair
        return (bool) ($key === $key_input);
    }


    //***************************************************************//
    // Function : get_common_info
    //---------------------------------------------------------------//
    // Params   : params: thuong la $this->data['Model']
    //---------------------------------------------------------------//
    // Return   : chuoi order by
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( tuanna ) ( Oct 20, 2008 )
    //***************************************************************//
    function get_common_info(&$array_info) {
        $arr = array();
        $uid = $this->Controller->Auth->user('id');

        // for created
        if (empty($array_info['id'])) {
            // Get create user
            if (empty($arr['create_user'])) {
                $arr['create_user'] = $uid;
            } else {
                $arr['create_user'] = $array_info['create_user'];
            }
        } else {
            // for updated
            // get modify user
            $arr['modify_user'] = $uid;
        }

        // set defaul status
        if (!isset($arr['status']))
            $arr['status'] = DEFAUL_STATUS;

        // merge array
        $array_info = am($array_info, $arr);

        if(empty($array_info['company_id'])){
            // set company id
            $comp = $this->Controller->Session->read( 'current_company');
            $array_info['company_id'] = $comp['id'];
        }

    }

    //***************************************************************//
    // Function : get_order_by
    //---------------------------------------------------------------//
    // Params   : params:tham so de tinh order by
    //          : fields : danh sach cac fields
    //---------------------------------------------------------------//
    // Return   : chuoi order by
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( tuanna ) ( Oct 20, 2008 )
    //***************************************************************//
    function get_order_by($params = array(), $fields = array()) {
        if (count($params) <= 0 || count($fields) <= 0 || empty($params["sort"]) == true) {
            return "";
        }

        // check sort
        if (empty($params["sort"]) == false) {
            $params["sort"] = $fields[$params["sort"]];
        }

        $order = $params["sort"];
        $direct = "asc";
        // check direction
        if (empty($params["direction"]) == false && in_array($params["direction"], array("asc", "desc")) == true) {
            $direct = $params["direction"];
        }

        // check page number
        if (empty($params["page"]) == true || is_numeric($params["page"]) == false) {
            $params["page"] = 1;
        }
        // return order by
        return $order . ' ' . $direct;
    }

    //***************************************************************//
    // Function : paginate
    //---------------------------------------------------------------//
    // Params   : sql, order , limit , page, recursive,extra
    //---------------------------------------------------------------//
    // Return   : paging
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( tuanna ) ( 26/07/2010 )
    //***************************************************************//
    function get_codetbl($code1 = null, $code2 = null, $value = null, $type = 'list', $status = null, $sorts = "value") {
        $types = array('all', 'first', 'count', 'neighbors', 'list', 'threaded');

        if (strlen($code1) == 0 && strlen($code2) == 0) {
            return array();
        }

        // kiem tra type duoc chon
        if (in_array($type, $types) == false) {
            $type = 'list';
        }

        // TÃ¡ÂºÂ¡o model Master
        App::import('Model', "Codetbl");
        $master = new Codetbl();

        // Ã„ï¿½iÃ¡Â»ï¿½u kiÃ¡Â»â€¡n tÃƒÂ¬m kiÃ¡ÂºÂ¿m
        $condition = array(
            "Codetbl.code1" => $code1,
            "Codetbl.code2" => $code2);
        if (strlen($value) > 0) {
            $condition["Codetbl.value"] = $value;
            $type = 'first';
        }

        if (isset($status)) {
            $condition["Codetbl.status"] = $status;
        }

        $list = $master->find($type, array('conditions' => $condition,
            'fields' => array("Codetbl.value", "Codetbl.name"),
            'order' => "Codetbl." . $sorts));

        return $list;
    }

    //***************************************************************//
    // Function : create_symlink
    //---------------------------------------------------------------//
    // Params   : $source, $dest, $force : ghi de hay ko
    //          :   $source: duong dan den file can tao shortcut
    //          :   $dest: thu muc
    //---------------------------------------------------------------//
    // Return   : paging
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( tuanna ) (  26/07/2010 )
    //***************************************************************//
    function create_symlink($source, $dest, $force = false) {
        //
        if (file_exists($source) == true && is_dir(substr($dest, 0, -1))) {
            $dest .= basename($source);
            if (file_exists($dest) == true) {
                if ($force == true) {
                    unlink($dest);           // xoa link cu
                    symlink($source, $dest); // tao symlink
                }
                chmod($dest, 0777);
                return true;
            }
            if (@symlink($source, $dest) == FALSE) {
                @unlink($dest);
                symlink($source, $dest); // tao symlink
            }
            chmod($dest, 0777);      // cho phep truy cap
            return true;
        }

        return false;
    }

    //***************************************************************//
    // Function : is_date
    //---------------------------------------------------------------//
    // Params   : $input_date : date need check
    //          : $mode       : ( default = 1 : dd/mm/yyyy
    //                                  else = 2: mm/dd/yyyy;
    //                                      else = 3: yyyy/mm/dd )
    //---------------------------------------------------------------//
    // Return   : true / false
    //---------------------------------------------------------------//
    // Memo     : kiem tra ngay nhap vao co dung hay ko
    //---------------------------------------------------------------//
    // Version  :  Add ( Nguyen Bao Nam ) ( Aug 27, 2008 )
    //***************************************************************//
    function is_date($input_date = null, $mode = "dmy") {

        //Nam nhap vao phai tu 1000-9999
        //Chuoi nhap vao phai co chieu dai la 10
        if (strlen($input_date) != 10) {
            return FALSE;
        }

        //Loai bo tat ca dau "/-\"
        //Nhung cai nao ki tu dat biet can them \ thi phai dat truoc
        $input_date = mb_ereg_replace("[-/]", '', $input_date);

        //Boi vi dau \ ko kiem tra bang regex dc nen danh xai` str_replace
        $input_date = str_replace("\\", "", $input_date);

        //Sau khi loai bo thi chieu dai chuoi ddmmyyyy phai bang = 8
        //Neu ko kiem tra thi ngay 2//11/2008 se tra ve TRUE
        if (strlen($input_date) != 8) {
            return FALSE;
        }

        //Kiem tra tinh hop le cua thang/ngay/nam
        if ($mode == "dmy") {
            //1: dd/mm/yyyy
            $Day = sprintf("%d", substr($input_date, 0, 2));
            $Month = sprintf("%d", substr($input_date, 2, 2));
            $Year = sprintf("%d", substr($input_date, 4, 4));
        } elseif ($mode == "mdy") {
            //2: mm/dd/yyyy
            $Month = sprintf("%d", substr($input_date, 0, 2));
            $Day = sprintf("%d", substr($input_date, 2, 2));
            $Year = sprintf("%d", substr($input_date, 4, 4));
        } elseif ($mode == "ymd") {
            //3: yyyy/mm/dd
            $Year = sprintf("%d", substr($input_date, 0, 4));
            $Month = sprintf("%d", substr($input_date, 4, 2));
            $Day = sprintf("%d", substr($input_date, 6, 2));
        }
        //The year is between 1 and 32767 inclusive.
        return checkdate($Month, $Day, $Year);
    }

    //***************************************************************//
    // Function : date_convert
    //---------------------------------------------------------------//
    // Params   :
    //---------------------------------------------------------------//
    // Return   :
    //---------------------------------------------------------------//
    // Memo     : convert date
    //---------------------------------------------------------------//
    // Version  :  Add ( tuanna ) ( Oct 24, 2008 )
    //***************************************************************//
    function date_convert($input = null, $typein = "dmy", $typeout = "ymd", $symbol = "/", $hour = false) {

        $input_root = $input;
        if ($hour == TRUE) {
            $hour = substr($input, 11, 8);
        }

        // bo gio
        $input = substr($input, 0, 10);

        //Kiem tra nguoi nhap co nhap dung hay khong truoc khi convert
        if ($this->is_date($input, $typein) == FALSE) {
            return $input;
        }

        if (strlen($input) == 10) {

            if ($typein == "ymd") {
                $year = substr($input, 0, 4);
                $month = substr($input, 5, 2);
                $day = substr($input, 8, 2);
            } elseif ($typein == "dmy") {
                $day = substr($input, 0, 2);
                $month = substr($input, 3, 2);
                $year = substr($input, 6, 4);
            }

            if ($typeout == "ymd") {
                $output = $year . $symbol . $month . $symbol . $day;
            } elseif ($typeout == "dmy") {
                $output = $day . $symbol . $month . $symbol . $year;
            }
            //Neu giu lai time
            if ($hour == TRUE) {
                return $output . " " . $hour;
            } else {
                return $output;
            }
        }
        return $input_root;
    }

    //***************************************************************//
    // Function : send_mail
    //---------------------------------------------------------------//
    // Params   : $data["to"] : to email
    //          : $data["bcc"] : to bcc email
    //          : $data["subject"] : subject email
    //          : $data["reply"] : reply to email
    //          : $data["from"] : from email
    //          : $data["template"] : template file, no '.ctp'
    //          : $data["type"] : 'both', 'text', 'html'
    //          : $data["data"] : data of email
    //---------------------------------------------------------------//
    // Return   : false / true
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( SONY ) ( Nov 18, 2008 )
    //***************************************************************//
    function send_mail($data) {
        App::uses('CakeEmail', 'Network/Email');

        $email = new CakeEmail('default');

        // neu user ko thuoc group admin hoac ko dang nhap thi cho send mail
        if (is_array($data) == false) {
            return false;
        }

        // get from
        if (isset($data["from"]) == false) {
            //$email->from(array(SUPPORT_EMAIL => BASE_NAME));
            $email->from(array($data["data"]['email'] => $data["data"]['fullname']));
        } else
            $email->from(array($data["from"] => BASE_NAME));

        // get to
        $this->Controller->Email->to = $data["to"];
        $email->to($data["to"]);
        if (isset($data["bcc"]) == true) {
            $email->bcc($data["bcc"]);
        }

        // subject
        $email->subject($data["subject"]);

        // reply
        if (isset($data["reply"]) == true) {
            $this->Controller->Email->replyTo = $data["reply"];
        }

        // template
        $email->template($data["template"], 'default');

        // type
        if (isset($data["type"]) == false) {
            $data["type"] = 'both';
        }

        // time
        $data["data"]["time"] = date("d/m/Y H:i:s");

        // set type
        $email->emailFormat($data["type"]);

        // set data
        $email->viewVars(array('data' => $data["data"]));

        try {
            $email->send();
        } catch (Exception $e) {
             echo 'Lỗi: ',  $e->getMessage(), "\n";
        }

        return true;
    }

    //***************************************************************//
    // Function : _SEO
    //---------------------------------------------------------------//
    // Params   : $string
    //---------------------------------------------------------------//
    // Return   : tieng viet khong dau
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( tuanna ) ( Nov 19, 2008 )
    //***************************************************************//
    function _SEO($str) {
        if (strlen($str) == 0)
            return $str;
        $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
        $str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
        $str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
        $str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
        $str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
        $str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
        $str = preg_replace("/(đ)/", 'd', $str);
        $str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
        $str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
        $str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
        $str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
        $str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
        $str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
        $str = preg_replace("/(Đ)/", 'D', $str);
        //$str = preg_replace("/( )/", '-', $str);
        $str = preg_replace("/[^0-9a-zA-Z_\-]/", ' ', $str);
        return $str;
    }


    //***************************************************************//
    // Function :
    //---------------------------------------------------------------//
    // Params   :$url : khong chua http://domain
    //---------------------------------------------------------------//
    // Return   :
    //---------------------------------------------------------------//
    // Memo     :
    //---------------------------------------------------------------//
    // Version  :  Add ( trint ) ( Mar 28, 2009 )
    //***************************************************************//
    function html_decode($string = null) {
        if (empty($string) == false) {
            $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
        }
        return $string;
    }

    /**
	 * Remore file by target_id
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function _delImageByTargetId($target_id, $Image = null) {
		if(empty($Image)) {
			App::uses('Image', 'Model');
			$Image = new Image();
		}

		$Image->getAll($target_id);

		if(!empty($images)) {
			foreach($images as $img){
				$path = PUBLIC_IMAGE_DETAIL.$img['Image']['image'];
				@unlink($path);
				$path = PUBLIC_IMAGE_THUMB.$img['Image']['image'];
				@unlink($path);
				$this->Image->delete($img['Image']['id']);
			}
		}
	}

	/**
	 * Remore file by id
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function _delImageByListId($data, $Image = null) {
		if(!empty($data)) {
			if(empty($Image)) {
				App::uses('Image', 'Model');
				$Image = new Image();
			}

			foreach($data as $id){
				if(!empty($id)) {
					$info = $Image->read(array('image'),(int)$id);
					if(!empty($info)) {
						$path = PUBLIC_IMAGE_DETAIL.$info['Image']['image'];
						@unlink($path);
						$path = PUBLIC_IMAGE_THUMB.$info['Image']['image'];
						@unlink($path);
						$Image->delete((int)$id);
					}
				}
			}
		}
	}
}

?>
